package com.sec.etech.presale.dao;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sec.etech.chain.customer.entity.ProjCustomer;
import com.sec.etech.chain.customer.mapper.ProjCustomerMapper;
import com.sec.etech.chain.customer.service.CusCustomerService;
import com.sec.etech.presale.model.CRM_PreProject;
import com.sec.etech.presale.service.CRM_PreProjectService;
import org.openbpm.base.core.id.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @version : 1.0
 * @auther : 老邓
 * @date : 2020/11/3 13:49
 * @description:
 */
@Component
public class CRM_PreProjectDao {

    @Autowired
    CRM_PreProjectService crm_preProjectService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Resource
    ProjCustomerMapper customerMapper;
    @Resource
    CusCustomerService customerService;

    //根据Npdfs1id获取S1数据
    public CRM_PreProject getS1ByNpdfs1id(String npdfs1id) {
        String sql = "SELECT * FROM pre_project_basicinfo WHERE npdfs1id=?";
        RowMapper<CRM_PreProject> rowMapper = new BeanPropertyRowMapper<>(CRM_PreProject.class);
        return jdbcTemplate.queryForObject(sql, rowMapper, npdfs1id);
    }

    //根据CRM的输入ID获取S1ID
    public String getNpdfs1Id(String crm_opportunity_id) {
        String npdfs1id;
        String sql = "SELECT npdfs1id FROM pre_project_basicinfo WHERE active=1 AND crm_opportunity_id=?";
        try {
            npdfs1id = jdbcTemplate.queryForObject(sql, new Object[]{crm_opportunity_id}, String.class);
        } catch (DataAccessException e) {
            return "0";
        }
        return npdfs1id;
    }

    //根据num获取S1ID
    public String getNpdfs1IdByNum(String num) {
        String npdfs1id;
        String sql = "SELECT npdfs1id FROM pre_project_basicinfo WHERE num=? LIMIT 1";
        try {
            npdfs1id = jdbcTemplate.queryForObject(sql, new Object[]{num}, String.class);
        } catch (DataAccessException e) {
            npdfs1id = "0";
        }
        return npdfs1id;
    }

    //根据名称获取ID（若没有则往配置表中同步添加)
    public String getDataId(String name, String scope, String name0) {
        if (StrUtil.isBlank(name)) return "0";
        String sql = "", id = "0";
        String tablename = (scope.equals("thermalperform") ? "prod_model" : "proj_project") + "_z_" + scope;
        sql = "SELECT " + scope + "id FROM " + tablename + " WHERE RTRIM(LTRIM(" + scope + "name))='" + name + "' LIMIT 1";
        if ("customergroup".equals(scope)){
            sql = "SELECT " + scope + "id FROM " + tablename + " WHERE RTRIM(LTRIM(customergroupfullname))='" + name0 + "' LIMIT 1";
        }
        try {
            id = jdbcTemplate.queryForObject(sql, String.class);
        } catch (DataAccessException e) {
            id = "0";
        }
        if (id.equals("0") && !scope.equals("province")) {
            id = IdUtil.getSuid();
            sql = "INSERT INTO " + tablename + "(";
            sql += scope + "id" + "," + scope + "name" + "," + scope + "code" + ",";
            sql += scope.equals("orderdprt") ? "dprtid" + "," : "";
            sql += scope.equals("duty") ? "dprtid" + "," + "S1dprtid" + "," + "S2dprtid" + "," + "S3dprtid" + "," + "S4dprtid" + "," : "";
            sql += scope.equals("plate") ? "fieldname" + "," : "";
            sql += scope.equals("customergroup") ? "customergroupfullname" + "," : "";
            sql += "active" + "," + "postuid" + "," + "lastuid" + "," + "postdate" + "," + "lastdate";
            sql += ") VALUES(";
            sql += id + "," + "'" + name + "'" + "," + "'CRM'" + ",";
            sql += scope.equals("orderdprt") ? "1" + "," : "";
            sql += scope.equals("duty") ? "1,1,1,1,1" + "," : "";
            sql += scope.equals("plate") || scope.equals("customergroup") ? "'" + name0 + "'" + "," : "";
            sql += "1,'417137619324108800','417137619324108800',NOW(),NOW()";
            sql += ")";
            jdbcTemplate.update(sql);
        }
        return id;
    }

    public String getDataId(String name, String scope) {
        return getDataId(name, scope, "");
    }

    //添加操作
    public String add(CRM_PreProject crm_preProject) {
        // 新增客户自动写入客户列表
        Long customerId = IdUtil.getUId();
        List<ProjCustomer> customerList = customerMapper.selectList(new LambdaQueryWrapper<ProjCustomer>()
                .eq(ProjCustomer::getActive, true)
                .eq(ProjCustomer::getCustomername, crm_preProject.getPlants()));
        if (customerList.size() > 0) {
            customerId = customerList.get(0).getCustomerid();
        }


        String id = IdUtil.getSuid();
        String sql = "INSERT INTO pre_project_basicinfo(";
        sql += "npdfs1id,num,projectname,schemeid,orderdprtid,dutyid,reformid,thermalperformid,customergroupid,plants,customerid,";
        sql += "instituteid,originid,salesmanageruname,quantity,plateid,country,marketid,projectremark,provinceid,";
        sql += "driveobjectid,supplyscopeid,crm_opportunity_id,active,presalestateid,";
        sql += "postuid,postdate,lastuid,lastdate";
        sql += ") VALUES(";
        sql += "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,";
        sql += "'417137619324108800',NOW(),'417137619324108800',NOW()";
        sql += ")";
        List<Object> paramList = new ArrayList<>();
        paramList.add(id);
        paramList.add(crm_preProject.getNum());
        paramList.add(crm_preProject.getProjectname());
        paramList.add(crm_preProject.getSchemeid());
        paramList.add(crm_preProject.getOrderdprtid());
        paramList.add(crm_preProject.getDutyid());
        paramList.add(crm_preProject.getReformid());
        paramList.add(crm_preProject.getThermalperformid());
        paramList.add(crm_preProject.getCustomergroupid());
        paramList.add(crm_preProject.getPlants());
        paramList.add(customerId);
        paramList.add(crm_preProject.getInstituteid());
        paramList.add(crm_preProject.getOriginid());
        paramList.add(crm_preProject.getSalesmanageruname());
        paramList.add(crm_preProject.getQuantity());
        paramList.add(crm_preProject.getPlateid());
        paramList.add(crm_preProject.getCountry());
        paramList.add(crm_preProject.getMarketid());
        paramList.add(crm_preProject.getProjectremark());
        paramList.add(crm_preProject.getProvinceid());
        paramList.add(crm_preProject.getDriveobjectid());
        paramList.add(crm_preProject.getSupplyscopeid());
        paramList.add(crm_preProject.getCrm_opportunity_id());
        paramList.add(crm_preProject.getActive());
        //售前项目状态设置为“咨询”
        paramList.add("1");
        jdbcTemplate.update(sql, paramList.toArray());
        sql = "INSERT INTO pre_project_heatinginfo(npdfs1id,capacity) VALUES(?,?)";
        List<Object> paramList1 = new ArrayList<>();
        paramList1.add(id);
        paramList1.add(crm_preProject.getCapacity());
        jdbcTemplate.update(sql, paramList1.toArray());
        // 新增客户自动写入客户列表
        if (customerList.size() == 0) {
            customerService.add(customerId, crm_preProject.getPlants(), "CRM", null, id);
        }

        return id;
    }

    //编辑操作
    public void edt(CRM_PreProject crm_preProject) {
        String sql = "UPDATE pre_project_basicinfo SET ";
        sql += "projectname=?,schemeid=?,orderdprtid=?,dutyid=?,reformid=?,thermalperformid=?,customergroupid=?,plants=?,";
        sql += "instituteid=?,originid=?,salesmanageruname=?,quantity=?,plateid=?,country=?,marketid=?,projectremark=?,provinceid=?,";
        sql += "driveobjectid=?,supplyscopeid=?,crm_opportunity_id=?,active=?,";
        sql += "lastuid='417137619324108800',lastdate=NOW()";
        sql += " WHERE npdfs1id=?";
        List<Object> paramList = new ArrayList<>();
        paramList.add(crm_preProject.getProjectname());
        paramList.add(crm_preProject.getSchemeid());
        paramList.add(crm_preProject.getOrderdprtid());
        paramList.add(crm_preProject.getDutyid());
        paramList.add(crm_preProject.getReformid());
        paramList.add(crm_preProject.getThermalperformid());
        paramList.add(crm_preProject.getCustomergroupid());
        paramList.add(crm_preProject.getPlants());
        paramList.add(crm_preProject.getInstituteid());
        paramList.add(crm_preProject.getOriginid());
        paramList.add(crm_preProject.getSalesmanageruname());
        paramList.add(crm_preProject.getQuantity());
        paramList.add(crm_preProject.getPlateid());
        paramList.add(crm_preProject.getCountry());
        paramList.add(crm_preProject.getMarketid());
        paramList.add(crm_preProject.getProjectremark());
        paramList.add(crm_preProject.getProvinceid());
        paramList.add(crm_preProject.getDriveobjectid());
        paramList.add(crm_preProject.getSupplyscopeid());
        paramList.add(crm_preProject.getCrm_opportunity_id());
        paramList.add(crm_preProject.getActive());
        paramList.add(crm_preProject.getNpdfs1id());
        jdbcTemplate.update(sql, paramList.toArray());
        sql = "UPDATE pre_project_heatinginfo SET capacity=? WHERE npdfs1id=?";
        List<Object> paramList1 = new ArrayList<>();
        paramList1.add(crm_preProject.getCapacity());
        paramList1.add(crm_preProject.getNpdfs1id());
        jdbcTemplate.update(sql, paramList1.toArray());
    }

    //编辑操作
    public void abandon(String npdfs1id) {
        String sql = "UPDATE pre_project_basicinfo SET active=0,lastuid='417137619324108800',lastdate=NOW()";
        sql += " WHERE npdfs1id=?";
        jdbcTemplate.update(sql, npdfs1id);
    }

    //写入投资方信息
    public void setCustomergroups(String npdfs1id, String customergroups) {
        String sql = "DELETE FROM pre_project_customergroups WHERE npdfs1id=?";
        jdbcTemplate.update(sql, new Object[]{npdfs1id});
        if (StrUtil.isBlank(customergroups)) return;
        String[] customergroupArrey = customergroups.replace("，", ",").split(",");
        String str = "";
        for (int i = 0; i < customergroupArrey.length; i++) {
            Map<String, String> customergroup = crm_preProjectService.getCustomergroupname(customergroupArrey[i]);
            String customergroupid = getDataId(customergroup.get("customergroupname"), "customergroup", customergroup.get("customergroupfullname"));
            if (!customergroupid.equals("0")) {
                String id = IdUtil.getSuid();
                sql = "INSERT INTO pre_project_customergroups(";
                sql += "customergroupsid,npdfs1id,customergroupid,active,orderby,postuid,postdate,lastuid,lastdate";
                sql += ") VALUES(";
                sql += "?,?,?,?,?,";
                sql += "'417137619324108800',NOW(),'417137619324108800',NOW()";
                sql += ")";
                List<Object> paramList = new ArrayList<>();
                paramList.add(id);
                paramList.add(npdfs1id);
                paramList.add(customergroupid);
                paramList.add(1);
                paramList.add(i + 1);
                jdbcTemplate.update(sql, paramList.toArray());
                if (str.equals("")) str += customergroup.get("customergroupname");
                else str += "、" + customergroup.get("customergroupname");
            }
        }
        if (StrUtil.isNotBlank(str)) {
            sql = "UPDATE pre_project_basicinfo SET customergroups=? WHERE npdfs1id=?";
            List<Object> paramList = new ArrayList<>();
            paramList.add(str);
            paramList.add(npdfs1id);
            jdbcTemplate.update(sql, paramList.toArray());
        }
    }

    //获取售前技术归口标识号
    public String getOrderdprtmarking(String orderdprtid) {
        String sql = "SELECT orderdprtmarking FROM proj_project_z_orderdprt WHERE orderdprtid=?";
        List<String> listData = jdbcTemplate.queryForList(sql, new Object[]{orderdprtid}, String.class);
        if (listData.isEmpty()) return "X";
        else return listData.get(0);
    }

}
